package cn.lyjuan.payment.third.base.model.chl.domain;

import cn.lyjuan.base.util.SpringContextHolder;
import cn.lyjuan.payment.third.base.common.enums.impl.ChlEnum;
import cn.lyjuan.payment.third.base.model.chl.domain.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ChlCnfScanner implements ApplicationListener<ContextRefreshedEvent> {

    private static Map<ChlEnum, Class<? extends IChlCnfModel>> CHLS = new HashMap<>();

    private static final Class CLASS_FLAG = IChlCnfFlag.class;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (null != event.getApplicationContext().getParent()) return;

        // 注册
        ChlCnfScanner.registry(ChlEnum.ALI, AliChlCnfModelImpl.class);
        ChlCnfScanner.registry(ChlEnum.WX_MP, WxMPChlCnfModelImpl.class);
        ChlCnfScanner.registry(ChlEnum.WX_OPEN, WxOpenChlCnfModeImpl.class);
        ChlCnfScanner.registry(ChlEnum.IAP, IapChlCnfModelImpl.class);
    }

    /**
     * @param chlType
     * @param cls
     */
    public static void registry(ChlEnum chlType, Class<? extends IChlCnfModel> cls) {
        if (log.isDebugEnabled())
            log.debug("registry: CHL-{} CLASS-{}", chlType, cls.getSimpleName());
        CHLS.put(chlType, cls);
    }

    /**
     * 扫描标识接口下的所有类，按要求注册
     */
    private void regitry() {
        // 加载 ICodeEnum 实现类
        String pkg = CLASS_FLAG.getPackage().getName();

        // 扫描类
        String path = CLASS_FLAG.getResource("./").getPath();
        File[] fs = new File(path).listFiles();
        String file = null;
        Class cls = null;
        for (File f : fs) {
            file = f.getName();
            if (!file.endsWith(".class")) continue;

            file = file.replace(".class", "");

            // 替换 / 为 .
            file = pkg + "." + file;

            // 加载
            try {
                cls = Class.forName(file);
            } catch (ClassNotFoundException e) {
                continue;
            }

            if (IChlCnfModel.class.isAssignableFrom(cls))
                CHLS.put(SpringContextHolder.getBean((Class<? extends IChlCnfModel>) cls).chl(), cls);
        }
    }

    /**
     * 根据渠道获取渠道配置域
     *
     * @param chl
     * @return
     */
    public static IChlCnfModel dispatch(ChlEnum chl) {
        Class<? extends IChlCnfModel> cls = CHLS.get(chl);

        if (null == cls)
            throw new RuntimeException("unsupported chl: " + chl);

        return SpringContextHolder.getBean(cls);
    }
}
